package com.example.barrage.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;

@Component
public class NettyServer {

    private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);

    @Value("${netty.port:8090}")
    private int port;

    private Channel serverChannel;

    @Autowired
    private ServerBootstrap serverBootstrap;

    @PostConstruct
    public void start() throws InterruptedException {
        logger.info("正在启动Netty服务器，端口: {}", port);
        serverChannel = serverBootstrap.bind(new InetSocketAddress(port)).sync().channel();
        logger.info("Netty服务器启动成功，端口: {}", port);
    }

    @PreDestroy
    public void stop() {
        logger.info("正在停止Netty服务器...");
        if (serverChannel != null) {
            serverChannel.close();
        }
        logger.info("Netty服务器已停止");
    }
}